package com.hsc.www.amqp.config;//package com.hsc.www.amqp.sender;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsc.www.amqp.util.CompleteCorrelationData;
import com.hsc.www.amqp.util.RabbitMetaMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p><b>Description:</b> RabbitMQ消息发送者
 * <p><b>Company:</b>
 *
 * @author created by hongda at 13:03 on 2017-10-24
 * @version V0.1
 */

@Component
public class RabbitSender {


    @Autowired
    RabbitTemplate rabbitTemplate;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 扩展消息的CorrelationData，方便在回调中应用
     */
    public void setCorrelationData(String coordinator) {
        rabbitTemplate.setCorrelationDataPostProcessor(((message, correlationData) ->
                new CompleteCorrelationData(correlationData != null ? correlationData.getId() : null, coordinator)));
    }


    /**
     * 发送MQ消息
     *
     * @param rabbitMetaMessage
     * @throws AmqpException
     * @throws JsonProcessingException
     */
    public void send(RabbitMetaMessage rabbitMetaMessage) throws AmqpException, JsonProcessingException {
        MessagePostProcessor messagePostProcessor = (message) -> {
            message.getMessageProperties().setMessageId(rabbitMetaMessage.getMessageId());
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);// 设置消息持久化
            return message;
        };
        rabbitTemplate.convertAndSend(rabbitMetaMessage.getExchange(), rabbitMetaMessage.getRoutingKey(),
                rabbitMetaMessage, messagePostProcessor, new MyCorrelationData(rabbitMetaMessage));
        logger.info("发送消息:{}", new ObjectMapper().writeValueAsString(rabbitMetaMessage));

    }


}
